//
//  HRPaymentManager.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-9-9.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRPaymentManager.h"
#import "PartnerConfig.h"
#import "DataSigner.h"

#import "DataVerifier.h"
#import "AlixPayOrder.h"

static HRPaymentManager *s_paymentManager = nil;
@interface HRPaymentManager()
@property(nonatomic,strong)paymentManagerBlock payBlock;
@property(nonatomic,strong)NSString *payNO;
@end

@implementation HRPaymentManager
+(HRPaymentManager*)shareInstant{
    if (!s_paymentManager) {
        s_paymentManager = [[HRPaymentManager alloc] init];
    }
    return s_paymentManager;
}



//加密
-(NSString*)doRsa:(NSString*)orderInfo
{
    id<DataSigner> signer;
    signer = CreateRSADataSigner(PartnerPrivKey);
    NSString *signedString = [signer signString:orderInfo];
    return signedString;
}

//wap回调函数
-(void)paymentResult:(NSString *)resultd
{
    //结果处理
#if ! __has_feature(objc_arc)
    AlixPayResult* result = [[[AlixPayResult alloc] initWithString:resultd] autorelease];
#else
    AlixPayResult* result = [[AlixPayResult alloc] initWithString:resultd];
#endif
	if (result)
    {
		
		if (result.statusCode == 9000)
        {
			/*
			 *用公钥验证签名 严格验证请使用result.resultString与result.signString验签
			 */
            
            //交易成功
            NSString* key = AlipayPubKey;//签约帐户后获取到的支付宝公钥
			id<DataVerifier> verifier;
            verifier = CreateRSADataVerifier(key);
            
			if ([verifier verifyString:result.resultString withSign:result.signString])
            {
                //验证签名成功，交易结果无篡改
                _payBlock(YES,result.statusMessage);
                //改变订单状态
                //[self updataOrderState:@"验证签名成功，交易结果无篡改"];
			}
        }
        else
        {
            _payBlock(NO,result.statusMessage);
        }
    }
    else
    {
        //失败
        _payBlock(NO,result.statusMessage);
    }
    
}

//客户端回调函数
-(void)cliectPaymentResult:(AlixPayResult *)result{
    if (result)
    {
		
		if (result.statusCode == 9000)
        {
			/*
			 *用公钥验证签名 严格验证请使用result.resultString与result.signString验签
			 */
            
            //交易成功
            NSString* key = AlipayPubKey;//签约帐户后获取到的支付宝公钥
			id<DataVerifier> verifier;
            verifier = CreateRSADataVerifier(key);
            
			if ([verifier verifyString:result.resultString withSign:result.signString])
            {
                //验证签名成功，交易结果无篡改
                _payBlock(YES,result.statusMessage);
                
                //[self updataOrderState:@"验证签名成功，交易结果无篡改"];
			}
        }
        else
        {
            _payBlock(NO,result.statusMessage);
        }
    }
    else
    {
        //失败
        _payBlock(NO,result.statusMessage);
    }

}

//刷新订单状态
-(void)updataOrderState:(NSString*)message{
    
    [HRInterfaceManager updateOrderPayState:self.payNO message:message completion:^(BOOL isSucceed, NSString *message, id data) {
        if (isSucceed) {
           _payBlock(YES,message);
        }else{
            _payBlock(NO,@"支付成功，但订单状态改变失败，请联系商家解决");
        }
    }];
}

-(void)paymentWithPayNo:(NSString*)payNo subject:(NSString*)subject body:(NSString*)body amount:(NSString*)amount completion:(paymentManagerBlock)completion{
    self.payNO = payNo;
    _payBlock = completion;
    NSString *appScheme = @"haierapp";
    AlixPayOrder *order = [[AlixPayOrder alloc] init];
    order.partner = PartnerID;
    order.seller = SellerID;
    
    order.tradeNO = payNo; //支付单（由商家自行制定）
    order.productName = subject; //商品标题
    order.productDescription = body; //商品描述
    order.amount = amount; //商品价格
    order.notifyURL = Alipay_NotifyURL; //回调URL
    
    NSString* orderInfo = [order description];
    NSString* signedStr = [[HRPaymentManager shareInstant] doRsa:orderInfo];
    NSLog(@"%@",signedStr);
    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                             orderInfo, signedStr, @"RSA"];
    
    [AlixLibService payOrder:orderString AndScheme:appScheme seletor:@selector(paymentResult:) target:self];
}



+(void)paymentWithOrderId:(NSString *)orderId subject:(NSString *)subject body:(NSString *)body amount:(NSString *)amount completion:(paymentManagerBlock)completion{
    //生成支付单
    [HRInterfaceManager savePayBill:orderId payMoney:amount paymentNo:@"alipay" completion:^(BOOL isSucceed, NSString *message, id data) {
        if (isSucceed) {
            [[HRPaymentManager shareInstant] paymentWithPayNo:[data objectForKey:@"payNo"] subject:subject body:body amount:amount completion:completion];
        }else{
            completion(NO,message);
        }
    }];

    
    
    
}



@end
